package com.e2oto.seller.common.download;

import android.os.Environment;
import com.e2oto.seller.common.Config;
import com.e2oto.seller.common.utils.RxBus;
import com.e2oto.seller.common.utils.fastjson.FastJsonConverterFactory;
import com.e2oto.seller.modules.seller.bean.RxBusBean;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * 基于Rxjava2+Retrofit2的 下载apk
 * Created by ZhangLiQiang on 2017/11/8.
 */

public class DownLoadManager {

    private static final String APK_DIR = Environment.getExternalStorageDirectory() + "/zh/seller/apk";

    private static final String APK_NAME = "zh_seller.apk";

    public static final int DOWNLOAD_ING = 4396;
    public static final int DOWNLOAD_ERROR = 4397;
    public static final int DOWNLOAD_SUCCESS = 4398;
    public static final int DOWNLOAD_START = 4399;

    /***
     * 用Rxbus 更新progress
     * @param url
     */
    public static void downLoad(String url) {

        new Retrofit.Builder()
                .baseUrl(Config.APP_HOST)
                .client(new OkHttpClient.Builder().addInterceptor(new ProgressInterceptor()).build())
                .addConverterFactory(FastJsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
                .create(DownLoadService.class)
                .download(url)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(@NonNull ResponseBody responseBody) throws Exception {
                        saveFile(responseBody);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        RxBus.getIntanceBus().post(new RxBusBean(DownLoadManager.DOWNLOAD_ERROR, throwable.toString()));
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        RxBus.getIntanceBus().post(new RxBusBean(DownLoadManager.DOWNLOAD_SUCCESS));
                    }
                }, new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        RxBus.getIntanceBus().post(new RxBusBean(DownLoadManager.DOWNLOAD_START));
                    }
                });
    }

    public static void saveFile(ResponseBody body) throws Exception {
        byte[] buf = new byte[2048];
        int len;
        InputStream is = body.byteStream();
        File dir = new File(APK_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(APK_DIR,APK_NAME);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream  fos = new FileOutputStream(file);
        while ((len = is.read(buf)) != -1) {
            fos.write(buf, 0, len);
        }
        fos.flush();
        if (is != null) is.close();
        if (fos != null) fos.close();
    }
}
